package org.xingyun.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.xingyun.bean.Provinces;
import org.xingyun.dao.ProvinceDao;
import org.xingyun.utils.JedisPoolUtils;
import redis.clients.jedis.Jedis;

import java.sql.SQLException;
import java.util.List;

public class ProvinceService {

    public String findAllProvince() throws SQLException, JsonProcessingException {
        //先从缓存找，找到就返回，如果没有，从数据库查，查到后，放到缓存中
        // 键 province

        Jedis jedis = JedisPoolUtils.getJedis();
        Boolean flag = jedis.exists("province");
        if (flag) {
            System.out.println("省份查询缓存");
            String province = jedis.get("province");
            return province;
        }
        //查数据库
        ProvinceDao provinceDao = new ProvinceDao();
        List<Provinces> list = provinceDao.getAll();
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(list);
        //放到缓存里
        jedis.set("province", s);

        return s;
    }
}
